package cn.java86;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author oldliu
 * @since 1.0
 */
public class Zhuanzhang {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }
        Connection con = null;
        PreparedStatement st = null;
        String url = "jdbc:mysql://localhost:3308/java86school?useUnicode=true&characterEncoding=utf8&useSSL=false" +
                "&serverTimezone=GMT%2B8";
        String user = "root";
        String pass = "root1234";
        String from="laoma",to="xiaowu";
        float money=200;
        try {
            con = DriverManager.getConnection(url, user, pass);
            con.setAutoCommit(false);
            String sql1="update bank set balance=balance-? where acno=?";
            String sql2="update bank set balance=balance+? where acno=?";
            st=con.prepareStatement(sql1);
            st.setFloat(1,money);
            st.setString(2,from);
            int r1=st.executeUpdate();
            st.close();
            st=con.prepareStatement(sql2);
            st.setFloat(1,money);
            st.setString(2,to);
            int r2=st.executeUpdate();
            if(r1>0 &&r2>0){
                con.commit();
                System.out.println("转账成功");
            }else{
                con.rollback();
                System.out.println("转账失败");
            }
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                st.close();
            } catch (Exception e) {

            }
            try {
                con.close();
            } catch (Exception e) {

            }
        }

    }
}
